import { defineStore } from "pinia";
import { ref } from 'vue';

type InfoType = {
    username: string,
    password: string,
    cname: string,
    avatar: string
}

export const userStore = defineStore(
    "user",
    () => {
        // 用户信息
        const userInfo = ref<InfoType | null>({
            username: "",
            password: "",
            cname: "",
            avatar: ""
        });

        // Token信息
        const accessToken = ref<string | null>(null);

        // 保存用户信息
        const setUserInfo = (val: InfoType) => {
            userInfo.value = val;
        }

        // 获取用户信息
        const getUserInfo = () => {
            return userInfo.value;
        }

        // 保存token
        const setToken = (val: string) => {
            accessToken.value = val;
        }

        // 获取用户信息
        const getToken = () => {
            return accessToken.value;
        }

        // 清空登录相关信息
        const clearLoginInfo = () => {
            userInfo.value = null;
            accessToken.value = null;
        }

        return {
            userInfo,
            setUserInfo,
            getUserInfo,
            accessToken,
            setToken,
            getToken,
            clearLoginInfo
        }
    },
    {
        // 配置持久化
        persist: {
          // 调整为兼容多端的API
          storage: {
            setItem(key, value) {
              uni.setStorageSync(key, value)
            },
            getItem(key) {
              return uni.getStorageSync(key)
            },
          },
        },
      }
)